#Copyright 2008, 2009 Daniele Trainini

#This file is part of dmote.

#dmote is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License version 2.0 as published
#by the Free Software Foundation

#dmote is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with dmote.  If not, see <http://www.gnu.org/licenses/>.


import sys
import os
from bluetooth import *

global rs

rs = 0

def spawner(file, args):
    pid = os.fork()
    if pid == 0:
        os.execvp(file, args)
    else:
        os.waitpid(pid, rs)


def sendlist(path, fileabs):
    lista = os.listdir(path)
    fileabs.writelines(":SELECT:\n")
    fileabs.writelines("Selezionare il file desiderato:\n")
    for i,j in enumerate(lista):
        fileabs.writelines(str(i)+" "+j+"\n")
    fileabs.writelines(":END:\n")
    fileabs.flush()
    return lista

def commandlist(fileabs, list):
    fileabs.writelines("Comandi:\n")
    for i in list:
        fileabs.writelines(i+'\n')

    fileabs.flush()


def mplayer(sock, fifo, film, sub, fas):
    
    comandi =["1 Volume down", "2 Mute", "3 Volume Up", "4 Rewind", "5 Pause","6 FastForward","7 FullScreen", "0 Exit"]
    
    try:
        lista = sendlist(film , fas)
        data = sock.recv(1024)
        title = lista[int(data.strip("'"))]
        subt = ""
        for i in os.listdir(sub):
            if i.startswith(title[:title.rfind('.')]):
                subt = sub+"/"+i


        mpid = os.fork()
        


        if mpid == 0:
            if subt:
                os.execlp("mplayer", "mplayer","-zoom", "-fs", "-slave", "-input", "file="+fifo, "-quiet","-sub", subt, film+title)
            else:
                os.execlp("mplayer", "mplayer","-zoom", "-fs", "-slave", "-input", "file="+fifo, "-quiet", film+title)

        commandlist(fas, comandi)
        pipe = open(fifo,"w", False)
        
        while True:
            data = sock.recv(128)
            if data.startswith(repr("5")):
                pipe.writelines("pause\n")
            elif data.startswith(repr("1")):
                pipe.writelines("volume -1\n")
            elif data.startswith(repr("2")):
                pipe.writelines("mute\n")
            elif data.startswith(repr("3")):
                pipe.writelines("volume 1\n")
            elif data.startswith(repr("6")):
                pipe.writelines("seek 1\n")
            elif data.startswith(repr("4")):
                pipe.writelines("seek -1\n")
            elif data.startswith(repr("7")):
                spawner("xte", ["xte", "key f"])
                        
            elif data.startswith(repr("0")):
                pipe.writelines("quit\n")
                pipe.close()
                os.waitpid(mpid, rs)
                break
        
    except IOError:
        pipe.close()
        
def music(sock, fifo, music ,fas):

    comandi =["1 Volume down", "2 Mute", "3 Volume Up", "4 Rewind", "5 Pause","6 FastForward", "7 Enqueue a Song", "8 Next Song", "0 Exit"]
    
    try:

        lista = sendlist(music , fas)
        data = sock.recv(1024)

        mupid = os.fork()
        if mupid == 0:
            os.execlp("mplayer", "mplayer", "-ao", "alsa", "-slave", "-input", "file="+fifo, "-quiet", music+"/"+lista[int(data.strip("'"))])

        commandlist(fas, comandi)
        pipe = open(fifo,"w", False)

        while True:
            data = sock.recv(128)
            if data.startswith(repr("1")):
                pipe.writelines("volume -1\n")
            elif data.startswith(repr("2")):
                pipe.writelines("mute\n")
            elif data.startswith(repr("3")):
                pipe.writelines("volume 1\n")
            elif data.startswith(repr("4")):
                pipe.writelines("seek -1\n")
            elif data.startswith(repr("5")):
                pipe.writelines("pause\n")
            elif data.startswith(repr("6")):
                pipe.writelines("seek 1\n")
            elif data.startswith(repr("7")):
                 lista = sendlist(music, fas)
                 data = sock.recv(1024)
                 pipe.writelines("loadfile "+music+"/"+lista[int(data.strip("'"))]+" 1 \n")

            elif data.startswith(repr("0")):
                pipe.writelines("quit\n")
                pipe.close()
                os.waitpid(mupid, rs)
                break
    
    except IOError:
        pipe.close()


def evince(sock, pdf, music, fas):

    comandi = ["1 FullScreen", "2 Previous", "3 Next", "4 Play a Song", "0 Exit"]

    pid = -1
    try:
        lista = sendlist(pdf , fas)
        print lista
        data = sock.recv(1024)
        
        epid = os.fork()
        
        if epid == 0:
            os.execlp("evince", "evince", pdf+"/"+ lista[int(data.strip("'"))])
            
        commandlist(fas, comandi)
        
        f5 = ["xte", "key F5"]
        right = ["xte", "key Right"]
        left  = ["xte", "key Left"]
        ctrl_l = ["xte", "keydown Control_L"]
        k_w = ["xte", "key w"]
        ctrl_lu = ["xte", "keyup Control_L"]
        while True:
            print "Evince waiting command"
            data = sock.recv(128)

            if data.startswith(repr("1")):
                spawner("xte", f5)
            elif data.startswith(repr("3")):
                spawner("xte", right)
            elif data.startswith(repr("2")):
                spawner("xte", left)
            elif data.startswith(repr("4")):
                lista = sendlist(music , fas)
                data = sock.recv(1024)
                pid = os.fork()
                if pid == 0:
                    os.execlp("mplayer", "mplayer", "-ao", "alsa", "-slave", "-quiet", music+"/"+lista[int(data.strip("'"))])

            elif data.startswith(repr("5")):
                if pid != -1:
                    os.kill(pid, 2)
                    os.waitpid(pid, rs)

            elif data.startswith(repr("0")):
                spawner("xte", ctrl_l)
                spawner("xte", k_w)
                spawner("xte", ctrl_lu)
                os.waitpid(epid, rs)
                break
    
    except IOError:
        pass

def eog(sock, pictd, music, fas):

    die = False
    pid = -1
    eogpid = os.fork()
    if eogpid == 0:
        os.execlp("eog", "eog", pictd+"/"+os.listdir(pictd)[0])

    comandi = ["1 FullScreen", "2 Previous", "3 Next", "4 Rotate", "5 Play a Song", "0 Exit"]

    commandlist(fas, comandi)

    f11 = ["xte", "key F11"]
    right = ["xte", "key Right"]
    left  = ["xte", "key Left"]
    ctrl_l = ["xte", "keydown Control_L"]
    k_r = ["xte", "key r"]
    k_w = ["xte", "key w"]
    ctrl_lu = ["xte", "keyup Control_L"]
    try:
        
        while True:
            data = sock.recv(128)
            if data.startswith(repr("1")):
                spawner("xte", f11)
            elif data.startswith(repr("3")):
                spawner("xte", right)
            elif data.startswith(repr("2")):
                spawner("xte",left)
            elif data.startswith(repr("4")):
                spawner("xte", ctrl_l)
                spawner("xte", k_r)
                spawner("xte", ctrl_lu)
            elif data.startswith(repr("5")):
                lista = sendlist(music , fas)
                data = sock.recv(1024)
                
                pid = os.fork()
                if pid == 0:
                    os.execlp("mplayer", "mplayer", "-ao", "alsa", "-slave", "-quiet", music+"/"+lista[int(data.strip("'"))])
                
            elif data.startswith(repr("6")):
                if pid != -1:
                    os.kill(pid, 2)
                    os.waitpid(pid, rs)

            elif data.startswith(repr("0")):
                spawner("xte", ctrl_l)
                spawner("xte", k_w)
                spawner("xte", ctrl_lu)
                os.waitpid(eogpid, rs)
                break
    
    except IOError:
        pass

home = os.getenv("HOME")

fifo = home+"/"+".dmote"+"/.mplayer"

pdf = home+"/"+".dmote"+"/Pdf"

film = home+"/"+".dmote"+"/Film/"

musicd = home+"/"+".dmote"+"/Music"

pictd = home+"/"+".dmote"+"/Pictures"

sub = home+"/"+".dmote"+"/Sub"

if not ".dmote" in os.listdir(home):
    os.mkdir(home+"/"+".dmote")
    os.mkdir(home+"/"+".dmote"+"/Film")
    os.mkdir(home+"/"+".dmote"+"/Pdf")
    os.mkdir(musicd)
    os.mkdir(pictd)
    os.mkdir(sub)
    os.mkfifo(home+"/"+".dmote"+"/.mplayer")

    print "~/.dmote created fill it with your files"

    exit(0)

server_sock = BluetoothSocket( RFCOMM )
server_sock.bind(("",1))
server_sock.listen(1)

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service( server_sock, "dmote",
                   service_id = uuid,
                   service_classes = [ uuid, SERIAL_PORT_CLASS ],
                   profiles = [ SERIAL_PORT_PROFILE ] )


print "Waiting for connection on RFCOMM channel %d" % port

client_sock, client_info = server_sock.accept()

print "Accepted connection from ", client_info

fas = client_sock.makefile('w')

comandi = ["1 Film", "2 Pdf", "3 Music", "4 Photos"]

while True:
    commandlist(fas, comandi)
    data = client_sock.recv(1024)
    if data.startswith(repr("1")):
        mplayer(client_sock, fifo, film, sub, fas)
    elif data.startswith(repr("2")):
        evince(client_sock, pdf, musicd, fas)
    elif data.startswith(repr("3")):
        music(client_sock, fifo, musicd, fas)
    elif data.startswith(repr("4")):
        eog(client_sock, pictd, musicd, fas)
    elif data.startswith(repr("0")):
        fas.writelines(":QUIT:\n")
        break


client_sock.close()
server_sock.close()

